import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

// 模拟球队数据
const mockTeams = [
  { id: 1, name: "皇家马德里" },
  { id: 2, name: "巴塞罗那" },
  { id: 3, name: "曼联" },
  { id: 4, name: "曼城" },
  { id: 5, name: "利物浦" },
  { id: 6, name: "切尔西" },
  { id: 7, name: "阿森纳" },
  { id: 8, name: "拜仁慕尼黑" },
  { id: 9, name: "多特蒙德" },
  { id: 10, name: "尤文图斯" },
  { id: 11, name: "AC米兰" },
  { id: 12, name: "国际米兰" },
  { id: 13, name: "巴黎圣日耳曼" },
  { id: 14, name: "马赛" },
  { id: 15, name: "里昂" },
];

// 模拟异步获取球队列表
export const fetchTeams = createAsyncThunk(
  'teams/fetchTeams',
  async (_, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      return mockTeams;
    } catch (error) {
      return rejectWithValue('获取球队列表失败');
    }
  }
);

// 模拟搜索球队
export const searchTeams = createAsyncThunk(
  'teams/searchTeams',
  async (searchTerm, { rejectWithValue }) => {
    try {
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      const filteredTeams = mockTeams.filter(team =>
        team.name.toLowerCase().includes(searchTerm.toLowerCase())
      );
      return filteredTeams;
    } catch (error) {
      return rejectWithValue('搜索球队失败');
    }
  }
);

const teamSlice = createSlice({
  name: 'teams',
  initialState: {
    teams: [],
    filteredTeams: [],
    searchTerm: '',
    loading: false,
    error: null,
    hasMore: true,
    currentPage: 1,
    pageSize: 10,
  },
  reducers: {
    setSearchTerm: (state, action) => {
      state.searchTerm = action.payload;
    },
    clearSearch: (state) => {
      state.searchTerm = '';
      state.filteredTeams = state.teams;
    },
    resetTeams: (state) => {
      state.teams = [];
      state.filteredTeams = [];
      state.searchTerm = '';
      state.currentPage = 1;
      state.hasMore = true;
    },
  },
  extraReducers: (builder) => {
    builder
      // 获取球队列表
      .addCase(fetchTeams.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchTeams.fulfilled, (state, action) => {
        state.loading = false;
        state.teams = action.payload;
        state.filteredTeams = action.payload;
        state.error = null;
      })
      .addCase(fetchTeams.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 搜索球队
      .addCase(searchTeams.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(searchTeams.fulfilled, (state, action) => {
        state.loading = false;
        state.filteredTeams = action.payload;
        state.error = null;
      })
      .addCase(searchTeams.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      });
  },
});

export const { setSearchTerm, clearSearch, resetTeams } = teamSlice.actions;
export default teamSlice.reducer;
